package com.qd.qx.ui.module2;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.animation.ScaleInAnimation;
import com.aspsine.irecyclerview.universaladapter.ViewHolderHelper;
import com.aspsine.irecyclerview.universaladapter.recyclerview.CommonRecycleViewAdapter;
import com.qd.common.base.BaseActivity;
import com.qd.common.baserx.RxBus;
import com.qd.common.baserx.RxManager;
import com.qd.common.baserx.RxSubscriber;
import com.qd.common.commonutils.ImageLoaderUtils;
import com.qd.common.commonutils.JsonUtils;
import com.qd.common.commonutils.ToastUitl;
import com.qd.common.commonwidget.LoadingDialog;
import com.qd.qx.R;
import com.qd.qx.api.Api;
import com.qd.qx.api.ApiServerConstants;
import com.qd.qx.api.MyXMPPTCPConnection;
import com.qd.qx.app.AppApplication;
import com.qd.qx.bean.MessageInfoBean;
import com.qd.qx.bean.PeopleContactsBean;
import com.qd.qx.bean.SearchAllSerBean;
import com.qd.qx.bean.SelectPathBean;
import com.qd.qx.bean.TongXunLuLocalBean;
import com.qd.qx.bean.TongxunluBean;
import com.qd.qx.bean.UserData;
import com.qd.qx.ui.main.activity.ChatActivity;
import com.qd.chatui.util.MyUtils;
import com.qd.qx.widget.DeleteEditText;
import com.qd.qx.widget.NineGridImageViewAdapter;

import org.jivesoftware.smackx.muc.MultiUserChat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Code is far away from bug with the animal protecting
 * Author：YS on 2018/11/5
 * Function：通讯录选人界面
 */
public class TongXunLuSelectActivity extends BaseActivity {
    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvAll)
    TextView tvAll;
    @BindView(R.id.tvSelect)
    TextView tvSelect;
    @BindView(R.id.ircv_selectitem)
    RecyclerView ircvSelectitem;
    @BindView(R.id.etSearch)
    DeleteEditText etSearch;
    @BindView(R.id.ircv_path)
    RecyclerView ircvPath;
    @BindView(R.id.txlChildIrcv)
    IRecyclerView txlChildIrcv;
    CommonRecycleViewAdapter itemShowAdapter;
    CommonRecycleViewAdapter selectAdapter;
    CommonRecycleViewAdapter pathAdapter;
    List<TongXunLuLocalBean> itemList = new ArrayList<>();//显示的集合

    List<TongXunLuLocalBean> selectList = new ArrayList<>();//选择的item集合

    List<SelectPathBean> pathList = new ArrayList<>();//路径集合
    String dpId;//部门编号
    String dpName;//部门名称
    View cylxrView;//常用联系人view
    String jid;//群号
    String localAccoutId;//已有的人 单人转群聊用
    String localName;//已有的人名字 单人转群聊用
    Map<String, Spanned> colorTemp = new HashMap<>();//存放变色的文本
    List<TongXunLuLocalBean> searchList = new ArrayList<>();//搜索后显示的集合
    List<TongXunLuLocalBean> serverList = new ArrayList<>();//服务器返回的集合
    private String leaderTag = "";//leader 的标识

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity, String dpId, String dpName, String jid, String localAccoutId, String localName) {
        Intent intent = new Intent(activity, TongXunLuSelectActivity.class);
        intent.putExtra("dpId", dpId);
        intent.putExtra("dpName", dpName);
        intent.putExtra("jid", jid);
        intent.putExtra("localAccoutId", localAccoutId);
        intent.putExtra("localName", localName);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                com.qd.common.R.anim.fade_out);
    }

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity, String dpId, String dpName) {
        Intent intent = new Intent(activity, TongXunLuSelectActivity.class);
        intent.putExtra("dpId", dpId);
        intent.putExtra("dpName", dpName);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                com.qd.common.R.anim.fade_out);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_tongxunlu_select;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        setData(intent);//新来的intent
        refreshActivty();
        super.onNewIntent(intent);
        if ((intent.getFlags() | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) > 0) {
            if (android.os.Build.VERSION.SDK_INT >= 19 && !isTaskRoot()) {
                ActivityManager tasksManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                tasksManager.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_NO_USER_ACTION);
            }
        }
    }

    @Override
    public void initView() {
        jid = getIntent().getStringExtra("jid");//jid 只拿一次
        localAccoutId = getIntent().getStringExtra("localAccoutId");//单聊转群聊用
        localName = getIntent().getStringExtra("localName");//单聊转群聊用
        if (!TextUtils.isEmpty(localAccoutId)) {
            TongXunLuLocalBean oldBean = new TongXunLuLocalBean();
            oldBean.setAccount(localAccoutId);
            oldBean.setName(localName);
            selectList.add(oldBean);
        }

        cylxrView = View.inflate(TongXunLuSelectActivity.this, R.layout.cylxr_itemview, null);
        tvTitle.setText("选择朋友");
        initItemAdapter();
        initSelectAdapter();
        initPathAdapter();
        setData(getIntent());
        searchAction();
    }

    /**
     * 搜索动作
     */
    private void searchAction() {
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    colorTemp.clear();
                    searchList.clear();
                    itemShowAdapter.replaceAll(itemList);
                    itemShowAdapter.notifyDataSetChanged();
                } else {
                    searchFromServer(s.toString());
                }
            }
        });
    }

    /**
     * 根据搜索的标记 转换集合
     *
     * @param keyWord
     */
    private void parseSearch(String keyWord) {
        colorTemp.clear();
        searchList.clear();
        for (TongXunLuLocalBean bean : itemList) {
            String bStr = bean.getName();
            if (bStr != null && bStr.contains(keyWord)) {
                int index = bStr.indexOf(keyWord);
                int len = keyWord.length();
                Spanned temp = Html.fromHtml(bStr.substring(0, index)
                        + "<font color=#3493d4>"
                        + bStr.substring(index, index + len) + "</font>"
                        + bStr.substring(index + len, bStr.length()));
                colorTemp.put(bStr, temp);
                searchList.add(bean);
            }
        }
        itemShowAdapter.replaceAll(searchList);
        itemShowAdapter.notifyDataSetChanged();
    }


    private void refreshActivty() {
        if (null != itemShowAdapter) {
            itemShowAdapter.notifyDataSetChanged();
        }
        if (null != selectAdapter) {
            selectAdapter.notifyDataSetChanged();
        }
        if (null != pathAdapter) {
            pathAdapter.replaceAll(pathList);
            pathAdapter.notifyDataSetChanged();
        }
    }

    private void setData(Intent intent) {
        dpId = intent.getStringExtra("dpId");
        if (TextUtils.isEmpty(dpId)) {
            dpId = "0";
        }
        dpName = intent.getStringExtra("dpName");
        switch (dpId) {
            case "0"://通讯录一级展示
                cylxrView.setVisibility(View.VISIBLE);
                requestAction();
                break;
            case "9527"://常用联系人
                cylxrView.setVisibility(View.GONE);
                requestContacts();
                break;
            default:
                cylxrView.setVisibility(View.GONE);
                requestAction();
                break;

        }
        clearPathList();
    }

    /**
     * 设置全选按钮的变化
     */
    private void setTvAllState() {
        boolean isAdd = isAllSelectOrUnSelect();//判断是添加还是删除
        if (isAdd) {
            tvAll.setText("全选");
        } else {
            tvAll.setText("取消");
        }
    }

    /**
     * 设置是否显示全选按钮
     */
    private void setShowSelectAll() {
        if ("0".equals(dpId)) {
            tvAll.setVisibility(View.GONE);
            return;
        }
        if (itemListIsHavePeople()) {
            tvAll.setVisibility(View.VISIBLE);
        } else {
            tvAll.setVisibility(View.GONE);
        }
        setTvAllState();
    }

    /**
     * 当前显示页面是否包含人
     *
     * @return
     */
    private boolean itemListIsHavePeople() {
        for (TongXunLuLocalBean bean : itemList) {
            if (bean.getType() == 0) {
                return true;
            }
        }
        return false;
    }

    private void clearPathList() {
        if (isLocalHave()) {
            List<SelectPathBean> newList = new ArrayList<>();
            for (SelectPathBean bean : pathList) {
                newList.add(bean);
                if (dpId.equals(bean.getDpId())) {
                    break;
                }
            }
            pathList.clear();
            pathList.addAll(newList);
        } else {
            pathList.add(new SelectPathBean(dpId, dpName));
        }

    }

    private boolean isLocalHave() {
        for (SelectPathBean bean : pathList) {
            if (dpId.equals(bean.getDpId())) {
                return true;
            }
        }
        return false;
    }

    private void initItemAdapter() {
        itemShowAdapter = new CommonRecycleViewAdapter<TongXunLuLocalBean>(this, R.layout.txl_ircv_itemlayout) {
            @Override
            public void convert(ViewHolderHelper helper, final TongXunLuLocalBean bean) {
                final ImageView ivSelect = helper.getView(R.id.iv_select);
                ImageView imageView = helper.getView(R.id.ivHeader);
                TextView tvName = helper.getView(R.id.tvName);
                TextView tvLeader = helper.getView(R.id.tvLeader);
                TextView tvAllCount = helper.getView(R.id.tvAllCount);
                ImageView imageLeader = helper.getView(R.id.ivLeader);
                tvAllCount.setVisibility(View.GONE);
                //0为人  1位部门
                if (0 == bean.getType()) {
                    ivSelect.setVisibility(View.VISIBLE);
                    setSelectAdapterShow(bean, ivSelect);
                    MyUtils.displayUserHeader(TongXunLuSelectActivity.this, imageView, bean.getHeadImg(), bean.getName());
                    if (leaderTag.equals(bean.getAccount())) {
                        imageLeader.setVisibility(View.VISIBLE);
                    } else {
                        imageLeader.setVisibility(View.GONE);
                    }
                    Spanned temp = colorTemp.get(bean.getName());
                    if (null != temp) {
                        tvName.setText(temp);
                    } else {
                        tvName.setText(bean.getName());
                    }
                    tvLeader.setText("");
                    tvAllCount.setText("");
                }

                if (1 == bean.getType()) {
                    ivSelect.setVisibility(View.GONE);
                    ImageLoaderUtils.display(TongXunLuSelectActivity.this, imageView, bean.getDeptHeadImg());
                    tvName.setText(bean.getDeptName());
                    //  tvLeader.setText("(负责人： " + bean.getLeader() + ")");
                    // tvAllCount.setText(bean.getTotalPeople() + "");
                }


                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (0 == bean.getType()) {
                            setSelectList(bean, ivSelect);
                            refreshShow();
                            setTvAllState();
                        } else if (1 == bean.getType()) {
                            TongXunLuSelectActivity.startAction(TongXunLuSelectActivity.this, bean.getDeptid(), bean.getDeptName());
                        }


                    }
                });
            }
        };
        txlChildIrcv.setLayoutManager(new LinearLayoutManager(TongXunLuSelectActivity.this));
        itemShowAdapter.addAll(itemList);
        itemShowAdapter.openLoadAnimation(new ScaleInAnimation());
        txlChildIrcv.setAdapter(itemShowAdapter);
        //设置常用联系人view
        txlChildIrcv.addHeaderView(cylxrView);
        cylxrView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TongXunLuSelectActivity.startAction(TongXunLuSelectActivity.this, "9527", "常用联系人");
            }
        });
    }

    private void requestAction() {
        Map<String, String> map = new HashMap<>();
        map.put("deptid", dpId);
        mRxManager.add((Api.getDefault().requestTongXunLu(Api.newRequestBody(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<MessageInfoBean>(TongXunLuSelectActivity.this, false) {
                    @Override
                    protected void _onNext(MessageInfoBean messageInfoBean) {
                        TongxunluBean tongxunluBean = (TongxunluBean) JsonUtils.ObjectToBean(messageInfoBean.getData(), TongxunluBean.class);
                        if (null == messageInfoBean) {
                            ToastUitl.showShort("数据有误");
                            return;
                        }
                        parseData(tongxunluBean);
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUitl.showShort("请求失败" + message);
                    }
                }));

    }

    /**
     * 解析数据到本地集合
     *
     * @param tongxunluBean
     */
    private void parseData(TongxunluBean tongxunluBean) {
        //解析数据到本地集合
        List<TongxunluBean.PeopleListBean> peopleListBeans = tongxunluBean.getPeopleList();
        TongXunLuLocalBean tongXunLuLocalBean = null;
        itemList.clear();
        if (null != peopleListBeans) {
            if (0 != peopleListBeans.size()) {
                leaderTag = peopleListBeans.get(0).getAccount();
            }
            for (TongxunluBean.PeopleListBean bean : peopleListBeans) {
                tongXunLuLocalBean = new TongXunLuLocalBean();
                tongXunLuLocalBean.setType(0);
                tongXunLuLocalBean.setAccount(bean.getAccount());
                tongXunLuLocalBean.setName(bean.getName());
                tongXunLuLocalBean.setDeptName(bean.getDeptName());
                tongXunLuLocalBean.setPositionName(bean.getPositionName());
                tongXunLuLocalBean.setRefCode(bean.getRefCode());
                tongXunLuLocalBean.setEmali(bean.getEmali());
                tongXunLuLocalBean.setPhone(bean.getPhone());
                tongXunLuLocalBean.setSex(bean.getSex());
                tongXunLuLocalBean.setManagerName(bean.getManagerName());
                tongXunLuLocalBean.setHeadImg(bean.getHeadImg());
                itemList.add(tongXunLuLocalBean);
            }
        }
        List<TongxunluBean.DeptListBean> deptListBeans = tongxunluBean.getDeptList();
        if (null != deptListBeans) {
            for (TongxunluBean.DeptListBean bean : deptListBeans) {
                tongXunLuLocalBean = new TongXunLuLocalBean();
                tongXunLuLocalBean.setType(1);
                tongXunLuLocalBean.setDeptid(bean.getDeptid());
                tongXunLuLocalBean.setDeptName(bean.getDeptName());
                tongXunLuLocalBean.setLeader(bean.getLeader());
                tongXunLuLocalBean.setTotalPeople(bean.getTotalPeople());
                tongXunLuLocalBean.setDeptHeadImg(bean.getDeptHeadImg());
                itemList.add(tongXunLuLocalBean);
            }
        }
        itemShowAdapter.replaceAll(itemList);
        itemShowAdapter.notifyDataSetChanged();
        setShowSelectAll();
    }

    /**
     * 头像9宫格适配器
     */
    private NineGridImageViewAdapter<String> nineGridImageViewAdapter = new NineGridImageViewAdapter<String>() {
        @Override
        protected void onDisplayImage(Context context, ImageView imageView, String photo) {
            ImageLoaderUtils.displaySmallRound(TongXunLuSelectActivity.this, imageView, photo);
        }

        @Override
        protected ImageView generateImageView(Context context) {
            return super.generateImageView(context);
        }
    };


    /**
     * 选择后的展示adapter
     */
    private void initSelectAdapter() {
        selectAdapter = new CommonRecycleViewAdapter<TongXunLuLocalBean>(TongXunLuSelectActivity.this, R.layout.select_itemimg_layout) {
            @Override
            public void convert(ViewHolderHelper helper, final TongXunLuLocalBean bean) {
                ImageView imageView = helper.getView(R.id.ivHeader);
                ImageView imageLeader = helper.getView(R.id.ivLeader);
                MyUtils.displayUserHeader(TongXunLuSelectActivity.this, imageView, bean.getHeadImg(), bean.getName());
                if (leaderTag.equals(bean.getAccount())) {
                    imageLeader.setVisibility(View.VISIBLE);
                } else {
                    imageLeader.setVisibility(View.GONE);
                }
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isSelectListHave(bean)) {
                            removeItemFromSelectList(bean);
                            refreshShow();
                        }
                    }
                });
            }
        };
        ircvSelectitem.setLayoutManager(new
                LinearLayoutManager(TongXunLuSelectActivity.this, LinearLayoutManager.HORIZONTAL, false));
        selectAdapter.addAll(selectList);
        ircvSelectitem.setAdapter(selectAdapter);
    }


    /**
     * 设置选中的最大宽度
     */
    private void setSelectWidth() {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ircvSelectitem.getLayoutParams();
        String sss = ircvSelectitem.getMeasuredWidth() + "";
        if (selectList.size() == 0) {
            ircvSelectitem.setVisibility(View.GONE);
        } else {
            ircvSelectitem.setVisibility(View.VISIBLE);
        }
        if (selectList.size() < 7) {
            ircvSelectitem.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        } else {
            layoutParams.width = ircvSelectitem.getMeasuredWidth();
            if (layoutParams.width < 756) {
                layoutParams.width = 756;
            }
            ircvSelectitem.setLayoutParams(layoutParams);
        }
        ircvSelectitem.scrollToPosition(selectList.size() - 1);
    }

    /**
     * 路径adapter
     */
    private void initPathAdapter() {
        pathAdapter = new CommonRecycleViewAdapter<SelectPathBean>(TongXunLuSelectActivity.this, R.layout.item_path_select_layout) {
            @Override
            public void convert(ViewHolderHelper helper, final SelectPathBean bean) {
                TextView textView = helper.getView(R.id.tvPath);
                textView.setText(bean.getDpName());
                if (bean.getDpId().equals(dpId)) {
                    textView.setCompoundDrawables(null, null, null, null);
                    TextPaint tp = textView.getPaint();
                    tp.setFakeBoldText(true);
                } else {
                    Drawable drawable = TongXunLuSelectActivity.this.getResources().getDrawable(R.drawable
                            .youjiantou);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    textView.setCompoundDrawables(null, null, drawable, null);
                    TextPaint tp = textView.getPaint();
                    tp.setFakeBoldText(false);
                }
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        colorTemp.clear();
                        searchList.clear();
                        etSearch.setText("");
                        TongXunLuSelectActivity.startAction(TongXunLuSelectActivity.this, bean.getDpId(), bean.getDpName());
                    }
                });
            }
        };
        ircvPath.setLayoutManager(new
                LinearLayoutManager(TongXunLuSelectActivity.this, LinearLayoutManager.HORIZONTAL, false));
        pathAdapter.addAll(pathList);
        ircvPath.setAdapter(pathAdapter);
    }

    /**
     * 设置选中集合 和图标状态
     *
     * @param bean
     * @param imageView
     */
    private void setSelectList(TongXunLuLocalBean bean, ImageView imageView) {
        if (isSelectListHave(bean)) {
            removeItemFromSelectList(bean);
            imageView.setBackgroundResource(R.drawable.xuanze_false);
        } else {
            selectList.add(bean);
            imageView.setBackgroundResource(R.drawable.xuanze_true);
        }
    }

    /**
     * 从选中集合总移除某个元素
     *
     * @param bean
     */
    private void removeItemFromSelectList(TongXunLuLocalBean bean) {
        Iterator<TongXunLuLocalBean> it = selectList.iterator();
        while (it.hasNext()) {
            TongXunLuLocalBean x = it.next();
            if (x.getRefCode().equals(bean.getRefCode())) {
                it.remove();
                break;
            }
        }
    }

    /**
     * selectadapter状态显示
     *
     * @param bean
     * @param imageView
     */
    private void setSelectAdapterShow(TongXunLuLocalBean bean, ImageView imageView) {
        if (isSelectListHave(bean)) {
            imageView.setBackgroundResource(R.drawable.xuanze_true);
        } else {
            imageView.setBackgroundResource(R.drawable.xuanze_false);
        }
    }

    /**
     * 判断本地选中集合是否包含该人
     *
     * @param bean
     * @return
     */
    private boolean isSelectListHave(TongXunLuLocalBean bean) {
        if (null == bean) {
            return false;
        }
        for (TongXunLuLocalBean bean1 : selectList) {
            if (bean1.getAccount().equals(bean.getAccount())) {
                return true;
            }
        }
        return false;
    }

    private void refreshShow() {

        if (selectList.size() == 0) {
            tvSelect.setText("选择");
            tvSelect.setTextColor(Color.parseColor("#39683c"));
        } else {
            tvSelect.setText("选择（" + selectList.size() + "）");
            tvSelect.setTextColor(Color.parseColor("#2ff13d"));
        }

        itemShowAdapter.notifyDataSetChanged();
        selectAdapter.replaceAll(selectList);
        selectAdapter.notifyDataSetChanged();
        pathAdapter.notifyDataSetChanged();
//        new Handler().postDelayed(new Runnable() {
//            public void run() {
//                setSelectWidth();
//            }
//        }, 200);
        setSelectWidth();
    }

    /**
     * 选择当前页全部的人
     */
    private void makeAll() {
        boolean isAdd = isAllSelectOrUnSelect();//判断是添加还是删除
        for (TongXunLuLocalBean bean : itemList) {
            if (bean.getType() == 0) {//人
                if (isAdd) {
                    //全部添加
                    if (!isSelectListHave(bean)) {
                        selectList.add(bean);
                    }
                } else {
                    //全部删除
                    if (isSelectListHave(bean)) {
                        removeItemFromSelectList(bean);
                    }
                }
            }
        }
        setTvAllState();
    }

    /**
     * 判断全选按钮 是添加操作 还是全部删除操作
     *
     * @return
     */
    private boolean isAllSelectOrUnSelect() {
        for (TongXunLuLocalBean bean : itemList) {
            if (bean.getType() == 0) {//人
                if (!isSelectListHave(bean)) {
                    return true;
                }
            }
        }
        return false;
    }

    @OnClick({R.id.ivBack, R.id.tvAll, R.id.tvSelect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvAll:
                makeAll();
                refreshShow();
                break;
            case R.id.tvSelect:
                if (null == selectList || selectList.size() == 0) {
                    return;
                }
                if (!TextUtils.isEmpty(localAccoutId)) {
                    //如果原有id不为空 那么执行创建群操作
                    threadCreatRoom();
                } else {
                    if (TextUtils.isEmpty(jid)) {
                        threadCreatRoom();
                    } else {
                        threadInvite(jid);
                    }
                }

                break;

        }
    }

    /**
     * 开线程执行 创建
     */
    private void threadCreatRoom() {
        LoadingDialog.showDialogForLoading(TongXunLuSelectActivity.this);
        new Thread() {
            @Override
            public void run() {
                super.run();
                creatRoom();
            }
        }.start();
    }

    /**
     * 创建群
     */
    private void creatRoom() {
        final List<String> inviteUsers = new ArrayList<>();
        String groupNickName = "";
        String groupTips = "";
        for (int i = 0; i < selectList.size(); i++) {
            if (!selectList.get(i).getName().equals(UserData.getInstance().getRealName())) {
                //拼接人的jid  名字+@+ip
                inviteUsers.add(selectList.get(i).getAccount() + "@" + ApiServerConstants.IM_URL);
                groupNickName = groupNickName + (selectList.get(i).getName() + ",");
            }

        }
        groupNickName = groupNickName.substring(0, groupNickName.length() - 1);
        groupTips = UserData.getInstance().getRealName() + "邀请" + groupNickName + "加入群聊";
        //控制长度
        if (groupNickName.length() > 10) {
            groupNickName = groupNickName.substring(0, 10) + "...";
        }

        final String finalGroupNickName = UserData.getInstance().getRealName() + "," + groupNickName;
        //创建群
        final String roomName = "Android" + System.currentTimeMillis();

        final String finalGroupTips = groupTips;
        MultiUserChat multiUserChat = MyXMPPTCPConnection.getInstance().createChatGroup(roomName, UserData.getInstance().getRealName(), inviteUsers, finalGroupNickName);
        LoadingDialog.cancelDialogForLoading();
        if (null != multiUserChat) {
            ChatActivity.startAction(TongXunLuSelectActivity.this, -1, multiUserChat.getRoom(), finalGroupNickName, finalGroupTips);
            finish();
        } else {
            ToastUitl.showShort("创建失败");
        }
    }

    /**
     * 开线程邀请
     *
     * @param jid
     */
    public void threadInvite(final String jid) {
        LoadingDialog.cancelDialogForLoading();
        new Thread() {
            @Override
            public void run() {
                super.run();
                invite(jid);
            }
        }.start();
    }

    /**
     * 邀请成员
     *
     * @param jid
     */
    private void invite(final String jid) {
        final List<String> inviteUsers = new ArrayList<>();
        String groupTips = "";
        for (int i = 0; i < selectList.size(); i++) {
            //拼接人的jid  名字+@+ip
            inviteUsers.add(selectList.get(i).getAccount() + "@" + ApiServerConstants.IM_URL);
            groupTips = groupTips + (selectList.get(i).getName() + ",");
        }
        groupTips = groupTips.substring(0, groupTips.length() - 1);
        groupTips = UserData.getInstance().getRealName() + "邀请" + groupTips + "加入群聊";
        final String finalGroupTips = groupTips;

        boolean flag = MyXMPPTCPConnection.getInstance().inviteGroupPeople(jid, inviteUsers, UserData.getInstance().getRealName());
        LoadingDialog.cancelDialogForLoading();
        if (flag) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    RxBus.getInstance().post("chatSendTips", finalGroupTips);
                    ToastUitl.showShort("邀请成功");
                }
            });

        } else {
            ToastUitl.showShort("邀请失败");
        }
        finish();
    }

    /**
     * 获取常用联系人列表
     */
    private void requestContacts() {
        Map<String, String> map = new HashMap<>();
        map.put("userCode", UserData.getInstance().getRefCode());
        if (null == mRxManager) {
            return;
        }
        mRxManager.add((Api.getDefault().getContacts(Api.newRequestBody(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<MessageInfoBean>(TongXunLuSelectActivity.this, false) {
                    @Override
                    protected void _onNext(MessageInfoBean messageInfoBean) {
                        PeopleContactsBean peopleContactsBean = (PeopleContactsBean) JsonUtils.ObjectToBean(messageInfoBean, PeopleContactsBean.class);
                        if (null != peopleContactsBean) {
                            List<PeopleContactsBean.DataBean> beanList = peopleContactsBean.getData();
                            if (null == beanList) {
                                return;
                            }
                            //解析数据到本地集合
                            TongXunLuLocalBean tongXunLuLocalBean = null;
                            itemList.clear();
                            for (PeopleContactsBean.DataBean bean : beanList) {
                                tongXunLuLocalBean = new TongXunLuLocalBean();
                                tongXunLuLocalBean.setType(0);
                                tongXunLuLocalBean.setAccount(bean.getAccount());
                                tongXunLuLocalBean.setName(bean.getName());
                                tongXunLuLocalBean.setDeptName(bean.getDeptName());
                                tongXunLuLocalBean.setPositionName(bean.getPositionName());
                                tongXunLuLocalBean.setRefCode(bean.getRefCode());
                                tongXunLuLocalBean.setEmali(bean.getEmali());
                                tongXunLuLocalBean.setPhone(bean.getPhone());
                                tongXunLuLocalBean.setSex(bean.getSex());
                                tongXunLuLocalBean.setManagerName(bean.getManagerName());
                                tongXunLuLocalBean.setHeadImg(bean.getHeadImg());
                                itemList.add(tongXunLuLocalBean);
                            }
                            itemShowAdapter.replaceAll(itemList);
                            itemShowAdapter.notifyDataSetChanged();
                            setShowSelectAll();
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUitl.showShort("请求失败" + message);
                    }
                }));

    }


    /**
     * 搜索
     *
     * @param searchStr
     */
    public void searchFromServer(final String searchStr) {
        Map<String, String> map = new HashMap<>();
        map.put("queryCriteria", searchStr);
        map.put("account", UserData.getInstance().getLoginName());
        if (TextUtils.isEmpty(dpId)) {
            return;
        }
        map.put("deptCode", dpId);
        RxManager mRxManager = new RxManager();
        mRxManager.add((Api.getDefault().searchAction(Api.newRequestBody(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<MessageInfoBean>(AppApplication.getAppContext(), false) {
                    @Override
                    protected void _onNext(MessageInfoBean messageInfoBean) {
                        SearchAllSerBean bean = (SearchAllSerBean) JsonUtils.ObjectToBean(messageInfoBean, SearchAllSerBean.class);
                        if (null != bean) {
                            parseData(bean, searchStr);
                        }

                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUitl.showShort(message);
                    }
                }));

    }

    private void parseData(SearchAllSerBean bean, String searchStr) {
        List<SearchAllSerBean.DataBean.UserlistBean> sList = bean.getData().getUserlist();
        TongXunLuLocalBean searchBean;
        serverList.clear();
        for (SearchAllSerBean.DataBean.UserlistBean b : sList) {
            searchBean = new TongXunLuLocalBean();
            searchBean.setType(0);
            searchBean.setName(b.getName());
            searchBean.setAccount(b.getAccount());
            searchBean.setDeptName(b.getDeptName());
            searchBean.setDeptBranc(b.getDeptBranc());
            searchBean.setPositionName(b.getPositionName());
            searchBean.setRefCode(b.getRefCode());
            searchBean.setEmali(b.getEmali());
            searchBean.setPhone(b.getPhone());
            searchBean.setSex(b.getSex());
            searchBean.setManagerName(b.getManagerName());
            searchBean.setHeadImg(b.getHeadImg());
            serverList.add(searchBean);
        }
        parseSearch(searchStr);
    }

}
